## structuredDict to RDataFrame.  Converts a structuredDict signal to an RDataFrame signal.  Should be a strait forward connect and send.

"""
<name>StructuredDict to DataFrame</name>
<description>Converts the structured dictionary class (a python signal class) to an RDataFrame signal class.  This puts the data from python into R.  Note that the data will be converted to a string using the python str() funciton.  This may cause a problem if your python dictionary contains classes or non-basic data types.  Please consider further manipulation before performing operations that would condense these kinds of data signals.</description>
<tags>Data Conversion</tags>
<RFunctions></RFunctions>
<icon></icon>
"""


from OWRpy import *
# import OWGUI
import signals
import redRGUI 


class structuredDictToDataFrame(OWRpy):
    def __init__(self, parent=None, signalManager=None):
        OWRpy.__init__(self, parent, signalManager, 'structuredDictToDataFrame')
        
        self.setRvariableNames(["conversionDataFrame"])
        
        self.inputs = [('Data', signals.StructuredDict, self.gotData)]
        self.outputs = [('Data', signals.RDataFrame)]
        
        ### GUI ###
        self.infoArea = redRGUI.textEdit(self.controlArea)
        self.infoArea.setHtml('Data not yet processed')
    def gotData(self, data):
        if data:
            ### start the conversion ###
            
            for name, item in data.getData().items():
                if name == 'row_names': continue
                self.R(str(name)+'<-c('+','.join(self.asCharacter(item))+')')
            colNames = []
            try:
                for i in data.getKeys():
                    if i == 'row_names': continue
                    colNames.append(str(i))
            except: ## likely an error of the keys
                for i in data.keys:
                    if i == 'row_names': continue
                    colNames.append(str(i))
            self.R(self.Rvariables['conversionDataFrame']+'<-data.frame('+','.join(colNames)+')')
            
            if 'row_names' in data.getData():
                self.R('rownames('+self.Rvariables['conversionDataFrame']+')<-c('+','.join(self.asCharacter(data.getData()['row_names']))+')')
            newData = signals.RDataFrame(data = self.Rvariables['conversionDataFrame'])
            self.rSend('Data', newData)
            self.infoArea.clear()
            try:
                text = data.showSummary()
            except Exception, msg:
                text = self.R('paste(capture.output(str('+str(self.Rvariables['conversionDataFrame'])+')), collapse = \'\\n\')')
            self.infoArea.setHtml('Your data has been processed. It looks like this now:</br></br><pre>'+str(text)+'</pre>')
        else:
            self.infoArea.setHtml('No data to process')
            
    def asCharacter(self, items):
        newItems = []
        for item in items:
            try:
                float(item)
                newItems.append(str(item))
            except:
                newItems.append('\''+str(item)+'\'')
            
        return newItems